package br.quest;

import android.app.Activity;
import android.content.SharedPreferences.Editor;

public class PreferenceManager {

    private static PreferenceManager instance;

    // The activity which will store all preferences. This should be the app main activity
    private Activity preferencesHolder;

    private PreferenceManager() {
    }

    /**
     * Returns an instance of PreferenceManager
     * 
     * @return The working instance of this manager.
     * @throws An Exception if it's not yet configured.
     */
    public static PreferenceManager get() throws Exception {
        if (instance == null)
            throw new NullPointerException("Manager not configured yet. Call PreferenceManager.configure() first.");
        return instance;
    }

    /**
     * Creates a single intance of PreferenceManager, passing a Context object. This method MUST be called before get(),
     * or else you'll get an Exception. This method must be called only once, preferably on the startup of your app.
     * 
     * @param holder The activity which will store all preferences. This should be the app main activity
     */
    public static void configure(Activity holder) {
        instance = new PreferenceManager();
        instance.preferencesHolder = holder;
        try {
            Config.loadConfigs();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public boolean savePreference(String key, Object value) {
        Editor e = preferencesHolder.getPreferences(0).edit();
        if (value instanceof String)
            e.putString(key, value.toString());
        else if (value instanceof Integer || value instanceof Short)
            e.putInt(key, (Integer) value);
        else if (value instanceof Double || value instanceof Float)
            e.putFloat(key, (Float) value);
        else if (value instanceof Boolean)
            e.putBoolean(key, (Boolean) value);
        else
            return false;
        return e.commit();
    }

    public String getString(String key, String defaultValue) {
        return preferencesHolder.getPreferences(0).getString(key, defaultValue);
    }

    public int getInt(String key, int defaultValue) {
        return preferencesHolder.getPreferences(0).getInt(key, defaultValue);
    }

    public float getFloat(String key, float defaultValue) {
        return preferencesHolder.getPreferences(0).getFloat(key, defaultValue);
    }

    public boolean getBoolean(String key, boolean defaultValue) {
        return preferencesHolder.getPreferences(0).getBoolean(key, defaultValue);
    }

}
